package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.annotation.CacheFind;
import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    //分页
    @Override
    public EasyUITable findItemByPage(int page, int rows) {
        //手写分页
        long total = itemMapper.selectCount(null);
        int startIndex = (page - 1) * rows;
        List<Item> item = itemMapper.findItemByPage(startIndex, rows);
        return new EasyUITable(total, item);

//        //mp实现分页
//        IPage mpPage = new Page(page,rows);
//        QueryWrapper <Item > queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("updated");
//        mpPage=itemMapper.selectPage(mpPage, queryWrapper);
//        long total =mpPage.getTotal();
//        List<Item> itemList =mpPage.getRecords();
//        return new EasyUITable(total,itemList);
    }

    //新增保存
    @Override
    @Transactional //开启事务控制 两个对象之间的操作
    public void saveItem(Item item, ItemDesc itemDesc) {
        item.setStatus(1);
        itemMapper.insert(item);
        itemDesc.setItemId(item.getId());
        itemDescMapper.insert(itemDesc);
    }
    //修改
    @Override
    public void updateItem(Item item, ItemDesc itemDesc) {
        itemMapper.updateById(item);
        itemDesc.setItemId(item.getId());
        itemDescMapper.updateById(itemDesc);
    }

    @Override
    public void deleteItem(Long[] ids) {

        //手动实现删除操作
        itemMapper.deleteItem(ids);
        //mp实现删除操作
        List<Long> list = Arrays.asList(ids);
        itemMapper.deleteBatchIds(list);
    }

    @Override
    public void updateStatus(Long[] ids, Integer status) {
        Item item = new Item();
        item.setStatus(status);
        //where id in (1,2,3,4)
//        UpdateWrapper<Item> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.in("id",Arrays.asList(ids));
//        itemMapper.update(item, updateWrapper);
        //mp实现上下架
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", Arrays.asList(ids));
        itemMapper.update(item, queryWrapper);
        //手动实现上下架
        itemMapper.updateStatus(ids, status);


    }
    //商品的检索查询
    @Override
    public ItemDesc findItemDescById(Long itemId) {
        return itemDescMapper.selectById(itemId);
    }


}
